<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完整订单流程测试</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ccc; }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .test-btn { padding: 8px 12px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .test-btn:hover { background: #0056b3; }
        .step { margin: 10px 0; padding: 10px; background: #f8f9fa; border-left: 4px solid #007bff; }
    </style>
</head>
<body>
    <h1>完整订单流程测试</h1>
    
    <div class="test-section">
        <h3>测试步骤</h3>
        <div class="step">
            <strong>步骤1:</strong> 模拟用户登录
            <button class="test-btn" onclick="step1_login()">执行登录</button>
            <div id="step1_result"></div>
        </div>
        
        <div class="step">
            <strong>步骤2:</strong> 创建新订单
            <button class="test-btn" onclick="step2_createOrder()">创建订单</button>
            <div id="step2_result"></div>
        </div>
        
        <div class="step">
            <strong>步骤3:</strong> 验证订单保存
            <button class="test-btn" onclick="step3_verifyOrder()">验证保存</button>
            <div id="step3_result"></div>
        </div>
        
        <div class="step">
            <strong>步骤4:</strong> 测试订单API
            <button class="test-btn" onclick="step4_testAPI()">测试API</button>
            <div id="step4_result"></div>
        </div>
        
        <div class="step">
            <strong>步骤5:</strong> 打开订单页面
            <button class="test-btn" onclick="step5_openOrders()">打开订单页面</button>
            <div id="step5_result"></div>
        </div>
    </div>
    
    <div class="test-section">
        <h3>调试信息</h3>
        <div id="debugInfo"></div>
    </div>
    
    <div class="test-section">
        <h3>控制台日志</h3>
        <div id="consoleLog"></div>
    </div>

    <!-- 引入必要的脚本 -->
    <script src="js/api.js"></script>
    <script src="js/auth.js"></script>
    
    <script>
        // 重写console.log来显示在页面上
        const originalLog = console.log;
        const originalWarn = console.warn;
        const originalError = console.error;
        
        function addToConsole(message, type = 'info') {
            const logDiv = document.getElementById('consoleLog');
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }
        
        console.log = function(...args) {
            originalLog.apply(console, args);
            addToConsole(args.join(' '), 'info');
        };
        
        console.warn = function(...args) {
            originalWarn.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        console.error = function(...args) {
            originalError.apply(console, args);
            addToConsole(args.join(' '), 'error');
        };
        
        let testOrderNumber = null;
        
        // 步骤1: 模拟用户登录
        function step1_login() {
            const resultDiv = document.getElementById('step1_result');
            try {
                const userData = {
                    username: 'Mike',
                    user_id: 'USER001',
                    email: 'mike@example.com',
                    phone: '1234567890',
                    user_type: 'Customer',
                    token: 'test-token-mike'
                };
                
                localStorage.setItem('currentUser', JSON.stringify(userData));
                localStorage.setItem('userData', JSON.stringify(userData));
                localStorage.setItem('authToken', userData.token);
                
                if (window.authManager) {
                    window.authManager.currentUser = userData;
                    window.authManager.isLoggedIn = true;
                    window.authManager.userType = userData.user_type;
                }
                
                resultDiv.innerHTML = '<div class="success">✓ 用户登录成功</div>';
                console.log('步骤1完成: 用户登录', userData);
                updateDebugInfo();
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 登录失败: ' + error.message + '</div>';
                console.error('步骤1失败:', error);
            }
        }
        
        // 步骤2: 创建新订单
        async function step2_createOrder() {
            const resultDiv = document.getElementById('step2_result');
            try {
                const orderData = {
                    items: [
                        {
                            productId: 'F003',
                            product_name: '流程测试商品',
                            price: 88.88,
                            quantity: 2
                        }
                    ],
                    shippingAddress: {
                        name: '流程测试用户',
                        phone: '13800138000',
                        address: '流程测试地址'
                    },
                    paymentMethod: 'alipay',
                    discount: 5
                };
                
                console.log('步骤2开始: 创建订单', orderData);
                const result = await window.api.createOrder(orderData);
                
                if (result.success) {
                    testOrderNumber = result.data.order_number;
                    resultDiv.innerHTML = `
                        <div class="success">✓ 订单创建成功</div>
                        <div class="info">订单号: ${testOrderNumber}</div>
                    `;
                    console.log('步骤2完成: 订单创建成功', result.data);
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 订单创建失败: ' + result.error + '</div>';
                    console.error('步骤2失败: 订单创建失败', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 创建订单错误: ' + error.message + '</div>';
                console.error('步骤2失败: 创建订单错误', error);
            }
        }
        
        // 步骤3: 验证订单保存
        async function step3_verifyOrder() {
            const resultDiv = document.getElementById('step3_result');
            try {
                console.log('步骤3开始: 验证订单保存');
                const result = await window.api.getOrders();
                
                if (result.success) {
                    const orders = result.data.orders || [];
                    const hasTestOrder = orders.some(order => order.order_number === testOrderNumber);
                    
                    if (hasTestOrder) {
                        resultDiv.innerHTML = `
                            <div class="success">✓ 订单已正确保存</div>
                            <div class="info">找到测试订单: ${testOrderNumber}</div>
                            <div class="info">总订单数: ${orders.length}</div>
                        `;
                        console.log('步骤3完成: 订单已正确保存', orders);
                    } else {
                        resultDiv.innerHTML = `
                            <div class="error">✗ 测试订单未找到</div>
                            <div class="info">总订单数: ${orders.length}</div>
                        `;
                        console.error('步骤3失败: 测试订单未找到');
                    }
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 获取订单失败: ' + result.error + '</div>';
                    console.error('步骤3失败: 获取订单失败', result.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 验证订单错误: ' + error.message + '</div>';
                console.error('步骤3失败: 验证订单错误', error);
            }
        }
        
        // 步骤4: 测试订单API
        async function step4_testAPI() {
            const resultDiv = document.getElementById('step4_result');
            try {
                console.log('步骤4开始: 测试订单API');
                
                // 测试获取订单列表
                const ordersResult = await window.api.getOrders();
                console.log('获取订单列表结果:', ordersResult);
                
                if (ordersResult.success && ordersResult.data.orders.length > 0) {
                    const firstOrder = ordersResult.data.orders[0];
                    
                    // 测试获取订单详情
                    const detailResult = await window.api.getOrderDetail(firstOrder.order_number);
                    console.log('获取订单详情结果:', detailResult);
                    
                    if (detailResult.success) {
                        resultDiv.innerHTML = `
                            <div class="success">✓ 订单API测试成功</div>
                            <div class="info">订单列表: ${ordersResult.data.orders.length} 个订单</div>
                            <div class="info">订单详情: 正常</div>
                        `;
                        console.log('步骤4完成: 订单API测试成功');
                    } else {
                        resultDiv.innerHTML = '<div class="error">✗ 订单详情API失败: ' + detailResult.error + '</div>';
                        console.error('步骤4失败: 订单详情API失败', detailResult.error);
                    }
                } else {
                    resultDiv.innerHTML = '<div class="error">✗ 订单列表API失败: ' + ordersResult.error + '</div>';
                    console.error('步骤4失败: 订单列表API失败', ordersResult.error);
                }
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ API测试错误: ' + error.message + '</div>';
                console.error('步骤4失败: API测试错误', error);
            }
        }
        
        // 步骤5: 打开订单页面
        function step5_openOrders() {
            const resultDiv = document.getElementById('step5_result');
            try {
                console.log('步骤5开始: 打开订单页面');
                window.open('orders.html', '_blank');
                resultDiv.innerHTML = '<div class="success">✓ 订单页面已打开</div>';
                console.log('步骤5完成: 订单页面已打开');
            } catch (error) {
                resultDiv.innerHTML = '<div class="error">✗ 打开订单页面失败: ' + error.message + '</div>';
                console.error('步骤5失败: 打开订单页面失败', error);
            }
        }
        
        // 更新调试信息
        function updateDebugInfo() {
            const debugDiv = document.getElementById('debugInfo');
            const authToken = localStorage.getItem('authToken');
            const userData = JSON.parse(localStorage.getItem('currentUser') || '{}');
            const isAuthenticated = window.authManager ? window.authManager.isAuthenticated() : false;
            
            debugDiv.innerHTML = `
                <div class="info">
                    <strong>认证Token:</strong> ${authToken || '无'}<br>
                    <strong>用户名:</strong> ${userData.username || '无'}<br>
                    <strong>认证状态:</strong> ${isAuthenticated ? '已认证' : '未认证'}<br>
                    <strong>测试订单号:</strong> ${testOrderNumber || '未创建'}
                </div>
            `;
        }
        
        // 页面加载完成后运行
        window.addEventListener('load', () => {
            console.log('完整订单流程测试页面加载完成');
            updateDebugInfo();
        });
    </script>
</body>
</html>
